//
//  RGPersonalPageVC.m
//  RedGrass
//
//  Created by wuyine on 2019/1/31.
//  Copyright © 2019年 hongcaosp. All rights reserved.
//

#import "RGPersonalPageVC.h"
//#import "RGMeView.h"
#import "HttpRequest.h"
#import "RGChatViewController.h"
#import "RGMyworkVediosViewController.h"
#import "RGShareView.h"
#import "RGCommentView.h"
#import "RGMeViewModel.h"
#import "RGCommentToolBarView.h"
#import "RGUserPageView.h"

@interface RGPersonalPageVC ()<RGUserPageViewDelegate,RGUserWorkViewDelegate,RGUserDynamicViewDelegate,RGShareViewDelegate,RGCommentViewDelegate,RGCommentToolBarViewDelegate>

//@property (strong, nonatomic) RGMeView *meView;
@property (nonatomic,strong) RGUserPageView *userPageView;
@property (strong, nonatomic) RGShareView *shareView;
@property (strong, nonatomic) RGCommentView *commentView;
@property (strong, nonatomic) RGCommentToolBarView *toolBarView;
@property (strong, nonatomic) RGMeViewModel *viewModel;

@end

@implementation RGPersonalPageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        //        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.NavStyleType = RGCustomNavStyleType_default; 
    [self showBackButton];
    RGUserInfoModel *user = [RGUserInfoModel getUserInfo];
    
    if(user.ID != _userId && _isScan == NO){
         [self showRightButton];
    }
    
    [self.customContentView addSubview:self.userPageView];
    [_userPageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    _userPageView.userId = self.userId;
//    [_userPageView loadData:self.userId];
}


-(void) viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_userPageView stopPlayingWhenCurrentVCIsNoteVisiable];
}

-(void) updatePersonalPageWithNickName:(NSString *)nickName meFollowmTa:(BOOL)meFollowmTa{
    if(_isScan){
        _nickName = nickName;
        _meFollowmTa = meFollowmTa;
        [self showRightButton];
    }
}


#pragma mark - reponse
- (void)addFocus:(UIButton *)btn {
    
    NSString *token = [RGUserInfoModel getUserInfo].token;
    NSDictionary *dic = @{@"id":@(_userId),
                          @"token":SafeStr(token)
                          };
    [self showLoading:@"正在关注Ta"];
    AA_WEAK_MAKE(self) weakSelf = self;
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/userFans/add"];
    [quest post:dic success:^(id data) {
        [weakSelf dismissLoading];
        [weakSelf showTextMessageWithMessage:@"成功关注Ta"];
        weakSelf.meFollowmTa = YES;
        if(weakSelf.focuStatusChangedBlock){
            weakSelf.focuStatusChangedBlock(weakSelf.meFollowmTa);
        }
        [weakSelf showRightButton];
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf showTextMessageWithMessage:message];
    }];
    
}

-(void)removeFocus:(UIButton *)btn{
    
    [self showLoading:@"正在取消关注Ta"];
    AA_WEAK_MAKE(self) weakSelf = self;
    NSString *token = [RGUserInfoModel getUserInfo].token;
    NSDictionary *dic = @{@"id":@(_userId),
                          @"token":SafeStr(token)
                          };
    
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/userFans/cancel"];
    [quest post:dic success:^(id data) {
        [weakSelf dismissLoading];
        [weakSelf showTextMessageWithMessage:@"成功取消关注Ta"];
        weakSelf.meFollowmTa = NO;
        if(weakSelf.focuStatusChangedBlock){
            weakSelf.focuStatusChangedBlock(weakSelf.meFollowmTa);
        }
        [weakSelf showRightButton];
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf showTextMessageWithMessage:message];
    }];
}

-(void)chatBtnClick:(UIButton *)button{
    NSInteger ID = [RGUserInfoModel getUserInfo].ID;
    if(ID == _userId){
        [self showTextMessageWithMessage:@"不能和自己发私信"];
    }else{
        RGChatViewController *vc = [[RGChatViewController alloc]init];
        vc.userId = ID;
        vc.toUserId = _userId;
        vc.nickName = _nickName;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - viewDelegate

-(void)cellItemChosedWithView:(NSIndexPath *)path dataList:(NSMutableArray *)array chosedTabIndex:(NSInteger)chosedTabIndex{
    
    if(chosedTabIndex == 0){
        RGMyworkVediosViewController *vc = [[RGMyworkVediosViewController alloc]init];
        [vc initViewWithVedioList:array index:path.row isLoadworkVedio:YES];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (chosedTabIndex == 2){
        RGMyworkVediosViewController *vc = [[RGMyworkVediosViewController alloc]init];
        [vc initViewWithVedioList:array index:path.row isLoadworkVedio:NO];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//点赞
-(void) favoriteVedioWithView:(NSIndexPath *)path vedioModel:(RGRecommendVideoModel *)model{
    [self.viewModel changeFavoriteStautswithIndexPath:path vedioModel:model];
}

//评论
-(void) comementVedioWithView:(NSIndexPath *)path vedioModel:(RGRecommendVideoModel *)model{
    _commentView = nil;
    _commentView.commentViewdelegate = nil;
    [self.commentView show];
    self.viewModel.currentVideoModel = model;
    [self.viewModel reInitProtocol];
    AA_WEAK_MAKE(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5), dispatch_get_main_queue(), ^{
        [weakSelf.viewModel gainVideoRecommentListWithIndexPath:path isGainMore:NO isShowLoading:YES vedioModel:model];
    });
}

//评论点赞

-(void) favoriteCommentWithView:(RGCommentView *)view chosedIndex:(NSInteger)index{
    [self.viewModel changeMainCommentFavoriteStautswithChosedIndex:index];
}

-(void) favoriteChildCommentWithView:(RGCommentView *)view chosedIndexPath:(NSIndexPath *)path{
    [self.viewModel changeChildCommentFavoriteStautswithChosedIndex:path];
}

//发表评论
-(void) addMainCommentWithView:(RGCommentView *)view content:(NSString *)content{
    [self.viewModel addMainCommentWithContent:content];
}

//发表子评论
-(void) addChildCommentWithView:(RGCommentView *)view path:(NSIndexPath *)currentPath chosedIndex:(NSInteger)index content:(NSString *)content{
    [self.viewModel addChildCommentWithContent:content chosedIndexPath:currentPath chosedIndex:index];
}

-(void) loadMainCommentListWithView:(RGCommentView *)view{
    [self.viewModel gainVideoRecommentListWithIsGainMore:NO];
}

-(void) loadMoreMainCommentListWithView:(RGCommentView *)view{
    [self.viewModel gainVideoRecommentListWithIsGainMore:YES];
}


//转发
-(void) shareVedioWithView:(NSIndexPath *)path vedioModel:(RGRecommendVideoModel *)model{
    self.zh_popupController = [zhPopupController new];
    self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
    self.zh_popupController.dismissOnMaskTouched = YES;
    self.zh_popupController.allowPan = YES;
    self.zh_popupController.slideStyle = zhPopupSlideStyleFromBottom;
    self.zh_popupController.maskAlpha = 0.2;
    self.viewModel.currentVideoModel = model;
    [self.viewModel reInitProtocol];
    //    [self.shareView initTopScrollViewWithUserArr:_testArr];
    self.shareView.chosedVedioIndex = path.row;
    [self.zh_popupController presentContentView:self.shareView duration:0.25 springAnimated:NO];
}

-(void) shareChosedWithView:(RGShareView *)view chosedIndex:(NSInteger)chosedIndex{
    
    [self.zh_popupController dismiss];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if(chosedIndex == kShareMessageTag){//私信
            [self.viewModel pushToChatVcWithChosedVedioIndex:view.chosedVedioIndex];
        }else if (chosedIndex == kSharePushToOtherTag){//转发
            self.toolBarView.currentIndex = view.chosedVedioIndex;
            [self.toolBarView show];
        }else if (chosedIndex == kShareToOtherTag){
            [self.viewModel shareToWeChatWithChosedVedioIndex:view.chosedVedioIndex];
        }else if (chosedIndex == kShareSaveTag){
            [self.viewModel downLoadVedioWithChosedVedioIndex:view.chosedVedioIndex];
        }
    });
}

//转发
-(void) onSendText:(NSString *)text WithView:(RGCommentToolBarView *)view{
    if([text length] && ![text isEqualToString:@"\n"]){
        //调用转发接口
        [self.viewModel shareVideoWithContent:text chosedIndex:view.currentIndex];
    }else{
        [self showTextMessageWithMessage:@"不能发送空内容"];
    }
}

//播放量
-(void) updateVedioPlayCountWithVedioId:(NSInteger)vedioId{
    [self.viewModel updateVeidoPlayCountsWithChosedVedioId:vedioId];
}

-(void) closeViewWithShareView{
    [self.zh_popupController dismiss];
}

#pragma mark - protocol

-(void) changeFavoriteStatusWithIsFavorite:(BOOL)isFavorite currentCellIndex:(NSInteger)index{
    [_userPageView startFavoriteAnimationWithIsFavorite:isFavorite cellIndex:index];
}


//评论成功 或者评论请求成功后，更新视图里面的评论数,
-(void) updateCommentCountsWhenCommentSuccessWithCellIndex:(NSInteger)cellIndex{
    [_userPageView updateCommentCountsWhenCommentSuccessWithCellIndex:_commentView.currentIndex];
}
//转发成功后更新转发数
-(void)updateforwardCountsWhenShareSuccessWithCellIndex:(NSInteger)cellIndex{
    [_userPageView updateforwardCountsWhenShareSuccessWithCellIndex:cellIndex];
}

//评论相关

-(void) reloadCommentTableViewWithCommentList:(NSMutableArray *)commentList{
    
    [_commentView reloadCommentTabelViewWithCommentList:commentList];
}

//点赞后刷新section
-(void) reloadCommentTableViewSectionWithIndex:(NSInteger)index{
    [_commentView changeFarvoriteStatusWithIndex:index];
}

//点赞子评论后刷新cell
-(void) reloadCommentTableViewCellWithIndexPath:(NSIndexPath *)path{
    [_commentView changeFarvoriteStatusWithIndexPath:path];
}

-(void) resetCommentStatusWhenPublicSuccess{
    [_commentView resetCommentStauts];
}

-(void) commentMjFooterEndLoading{
    [_commentView commentMjFooterLoadingEnd];
}

-(void) commentMjHeaderEndLoading{
    [_commentView commentMjHeaderLoadingEnd];
}

-(void) changeCommentMjFooterStatusWithNoMoreData{
    [_commentView setCommentMjFooterStatusWithNoMoreData];
}

-(void) showAlertWhenFarvoriteSelfComment{
    [_commentView showAlertWhenFarvoriteSelfComment];
}

-(void) showAlertWhenCommentSelfComment{
    [_commentView showAlertWhenCommentSelfComment];
}

//dismisstoolbarview
-(void) dismissToolBarView{
    [_toolBarView dismiss];
}



#pragma mark - getter
//-(RGMeView *)meView{
//    if(!_meView){
//        _meView = [[RGMeView alloc]init];
//        _meView.meViewDelegate = self;
//    }
//    return _meView;
//}

- (RGUserPageView *)userPageView {
    if (!_userPageView) {
        _userPageView = [[RGUserPageView alloc] init];
        _userPageView.meViewDelegate = self;
        _userPageView.userDynamicViewDelegate = self;
        _userPageView.userWorkViewDelegate = self;
    }
    return _userPageView;
}

-(void)showRightButton{
    if(_meFollowmTa){
        
        UIButton * right1 = [UIButton buttonWithType:UIButtonTypeCustom];
        right1.frame = CGRectMake(0, kNavigationBtnSpaceHorizontal, 50, 30);
//        [right setTintColor:[UIColor whiteColor]];
//        [right setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [right1.titleLabel setFont:[UIFont systemFontOfSize:15.0]];
        [right1 setTitle:@"已关注" forState:UIControlStateNormal];
        [right1 addTarget:self action:@selector(removeFocus:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *right2 = [UIButton buttonWithType:UIButtonTypeCustom];
        right2.frame = CGRectMake(0, 0, 30, 30);
        [right2 setImage:IMAGE_NAMED(@"发送消息") forState:UIControlStateNormal];
        [right2 addTarget:self action:@selector(chatBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.customNavBar.rightButtons = @[right1, right2];
    }else{
        UIButton * right = [UIButton buttonWithType:UIButtonTypeCustom];
        right.frame = CGRectMake(0, kNavigationBtnSpaceHorizontal, 80, 30);
        [right setTintColor:[UIColor whiteColor]];
        [right setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [right.titleLabel setFont:[UIFont systemFontOfSize:15.0]];
        [right setTitle:@"+ 关注" forState:UIControlStateNormal];
        right.backgroundColor = UICOLOR_WITH_RGBINT(0xf73152);
        right.layer.cornerRadius = 4;
        right.layer.masksToBounds = YES;
        [right addTarget:self action:@selector(addFocus:) forControlEvents:UIControlEventTouchUpInside];
        self.customNavBar.rightButtons = @[right];
    }
}

-(RGShareView *)shareView{
    if(!_shareView){
        CGFloat Height = KIsiPhoneX ? (150 + 34):150;
        _shareView = [[RGShareView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, Height)];
        _shareView.shareViewDelegate = self;
    }
    return _shareView;
}

-(RGCommentView *)commentView{
    if(!_commentView){
        _commentView = [[RGCommentView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
        _commentView.commentViewdelegate = self;
    }
    return _commentView;
}

-(RGCommentToolBarView *)toolBarView{
    if(!_toolBarView){
        _toolBarView = [[RGCommentToolBarView alloc]init];
        _toolBarView.isShowBackGround = YES;
        _toolBarView.delegate = self;
    }
    return _toolBarView;
}


-(RGMeViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[RGMeViewModel alloc]initWithProtocol:self];
    }
    return _viewModel;
}


@end
